package org.dandsoft.blackbox.knowledge;

import java.io.*;
import java.util.LinkedList;
import java.util.Iterator;

/**
 * User: dvilyuzhanin
 * Date: 15.01.2009 15:07:58
 */
public class ImageContentInfo extends AbstractInfo<ImageContentInfo> {
    public final static String TYPE = "data";
    public final static DataFormat FORMAT = DataFormat.Binary;
    private byte[] data;
    private static final int BUFFER_SIZE = 1024;

    public ImageContentInfo() {
        super(ImageInfo.IMAGE_GROUP_NAME, TYPE, FORMAT);
    }

    public void store(OutputStream out) throws IOException {
        DataOutputStream dataOut = new DataOutputStream(out);
        if (data != null) {
            dataOut.write(data);
        }
    }

    public void load(InputStream in) throws IOException {
        LinkedList<byte[]> buffers = new LinkedList<byte[]>();
        int bytesCount = -1;
        int totalCount = 0;
        byte[] buffer;
        do {
            buffer = new byte[BUFFER_SIZE];
            bytesCount = in.read(buffer);
            totalCount += bytesCount;
            buffers.add(buffer);
        } while (bytesCount == buffer.length);

        byte[] data = new byte[totalCount];
        int beginIndex = 0;
        Iterator<byte[]> iter = buffers.iterator();
        while (iter.hasNext()) {
            byte[] currentBuffer = iter.next();
            int length = currentBuffer.length;
            if (!iter.hasNext()) {
                length = bytesCount;
            }
            System.arraycopy(currentBuffer, 0, data, beginIndex, length);
            beginIndex += length;
        }
        this.data = data;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }
}
